<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="
      level
        ? `${optionInfo?.type === 'add' ? '新建' : '编辑'}商品${level === 1 ? '一' : level === 2 ? '二' : '三'}级分类`
        : '新建商品一级分类'
    "
    width="780"
    @close="closeDialog"
  >
    <!-- 一级分类 -->
    <el-form v-if="level === 1" :model="form1" ref="form1Ref" :rules="rules" label-width="80">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model.trim="form1.name"
          style="width: 100%"
          maxlength="10"
          placeholder="请填写一级商品分类名称"
          @input="levelNameChange()"
          oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
        >
          <template #suffix> {{ form1.strNUm }}/10 </template>
        </el-input>
      </el-form-item>
      <el-form-item label="分类备注" prop="tips">
        <el-input
          :disabled="optionInfo.type === 'edit' && level !== 1"
          v-model.trim="form1.tips"
          type="textarea"
          maxlength="40"
          :rows="2"
          placeholder="请填写分类描述备注用于记忆非必填项"
          oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
        ></el-input>
      </el-form-item>
      <el-form-item label="排列顺序" prop="sort">
        <el-input v-model="form1.sort" type="number" min="1" placeholder="排序“0”则按照创建顺序排序"></el-input>
      </el-form-item>
      <el-form-item label="分类icon">
        <AliOssUpload
          :fileList="form1.image"
          listType="picture-card"
          @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, form1)"
          :maxLength="1"
          :maxSize="5"
        >
        </AliOssUpload>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form1.status">
          <el-radio label="1">显示</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 二级分类 -->
    <el-form v-else-if="level === 2" :model="form2" ref="form2Ref" :rules="rules" label-width="80">
      <el-form-item label="一级分类" prop="level1">
        <el-select v-model="form2.level1" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in level1Class" :label="item.name" :value="item.categoryId" :key="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类备注" prop="tips">
        <el-input
          disabled
          v-model.trim="form2.tips"
          type="textarea"
          maxlength="40"
          :rows="2"
          placeholder="请填写分类描述备注用于记忆非必填项"
          oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
        ></el-input>
      </el-form-item>
      <el-form-item label="二级分类" prop="level2">
        <el-input v-model="form2.level2" style="display: none"></el-input>
        <div style="max-height: 400px; overflow-y: auto; width: 100%">
          <div v-for="(item, index) in form2.level2" :key="index" class="level2-list">
            <el-input
              v-show="item.delFlag === 0"
              v-model.trim="form2.level2[index].name"
              style="height: fit-content; width: 300px"
              maxlength="10"
              placeholder="请填写二级商品分类名称"
              @input="levelNameChange(item)"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            >
              <template #suffix> {{ item.strNUm }}/10 </template>
            </el-input>

            <div class="level2-sort-wrap" v-show="item.delFlag === 0">
              <span>顺序号</span>
              <el-input type="number" v-model="form2.level2[index].sort" min="1" style="width: 80px"> </el-input>
            </div>

            <div class="level2-sort-wrap" v-show="item.delFlag === 0">
              <span>分类icon</span>
              <div class="image-box">
                <AliOssUpload
                  :fileList="form2.level2[index].image"
                  listType="picture-card"
                  @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, form2.level2[index])"
                  :maxLength="1"
                  :maxSize="5"
                >
                </AliOssUpload>
              </div>
              <el-icon class="del-icon" @click="delLevelItem(item, index)"><Delete /></el-icon>
            </div>
          </div>
        </div>

        <el-button v-show="optionInfo.type === 'add'" type="primary" :icon="Plus" link @click="addItem" style="margin-top: 10px"
          >继续添加</el-button
        >
      </el-form-item>
      <!-- <el-form-item label="分类icon">
        <AliOssUpload
          :fileList="form2.image"
          listType="picture-card"
          @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, form2)"
          :maxLength="1"
          :maxSize="5"
        >
        </AliOssUpload>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form2.status">
          <el-radio label="1">显示</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 三级分类 -->
    <el-form v-else-if="level === 3" :model="form3" ref="form3Ref" :rules="rules" label-width="80">
      <el-form-item label="一级分类" prop="level1">
        <el-select v-model="form3.level1" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in level1Class" :label="item.name" :value="item.categoryId" :key="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类备注" prop="tips">
        <el-input
          disabled
          v-model.trim="form3.tips"
          type="textarea"
          maxlength="40"
          :rows="2"
          placeholder="请填写分类描述备注用于记忆非必填项"
          oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
        ></el-input>
      </el-form-item>
      <el-form-item label="二级分类" prop="level2">
        <el-select v-model="form3.level2" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in level2Class" :label="item.name" :value="item.categoryId" :key="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类" prop="level3">
        <el-input v-model="form3.level3" style="display: none"></el-input>
        <div style="max-height: 400px; overflow-y: auto">
          <div v-for="(item, index) in form3.level3" :key="index" class="level2-list">
            <el-input
              v-show="item.delFlag === 0"
              v-model.trim="form3.level3[index].name"
              style="height: fit-content; width: 300px"
              maxlength="10"
              placeholder="请填写三级商品分类名称"
              @input="levelNameChange(item)"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            >
              <template #suffix> {{ item.strNUm }}/10 </template>
            </el-input>

            <div class="level2-sort-wrap" v-show="item.delFlag === 0">
              <span>顺序号</span>
              <el-input type="number" v-model="form3.level3[index].sort" min="1" style="width: 80px"> </el-input>
            </div>

            <div class="level2-sort-wrap" v-show="item.delFlag === 0">
              <span>分类icon</span>
              <div class="image-box">
                <AliOssUpload
                  :fileList="form3.level3[index].image"
                  listType="picture-card"
                  @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, form3.level3[index])"
                  :maxLength="1"
                  :maxSize="5"
                >
                </AliOssUpload>
              </div>
              <el-icon class="del-icon" @click="delLevelItem(item, index)"><Delete /></el-icon>
            </div>
          </div>
        </div>

        <el-button type="primary" v-show="optionInfo.type === 'add'" :icon="Plus" link @click="addItem" style="margin-top: 10px"
          >继续添加</el-button
        >
      </el-form-item>
      <!-- <el-form-item label="分类icon">
        <AliOssUpload
          :fileList="form3.image"
          listType="picture-card"
          @uploadSuccess="(file, fileList) => uploadSuccess(file, fileList, form3)"
          :maxLength="1"
          :maxSize="5"
        >
        </AliOssUpload>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form3.status">
          <el-radio label="1">显示</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch, ref, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { orgChildIdFindParent } from "@/utils/index";
import AliOssUpload from "@/components/AliOssUpload";

const emit = defineEmits(["close", "submit"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        type: "add", //add edit
        formData: {},
        list: []
      };
    }
  }
});

watch(
  () => props.optionInfo,
  val => {
    console.log("form组件收到的数据===", val);
    dialogFormVisible.value = val?.isShow;
    level.value = val?.formData?.fomart ? val?.formData?.fomart.split("-").length : 0;
    if (!val?.formData?.categoryId) {
      nextTick(() => {
        //添加一级分类时，清空form1表单数据
        form1Ref.value.resetFields();
      });
    }
    if (val.type === "add") {
      level.value = level.value + 1;
    }
    if (val.type === "edit") {
      selectReview(val?.formData, "edit"); //编辑，回显父级的分类下拉数据
      // 编辑的时候，数据回显
      reviewForm(val.formData);
    } else if (val.type === "add") {
      //添加的时候，回显父级分类
      selectReview(val?.formData, "add"); //添加，回显父级的分类下拉数据
      reviewLevel(val.formData);
    }
  },
  { deep: true }
);

const level1Class = ref([]);
const level2Class = ref([]);
const level = ref(0);
const form1Ref = ref();
const form2Ref = ref();
const form3Ref = ref();
const dialogFormVisible = ref(props.optionInfo.isShow);
const form1 = ref({
  name: "",
  tips: "",
  sort: 1,
  status: "1",
  strNUm: 0
});
const form2 = ref({
  level1: "",
  level2: [{ name: "", sort: 1, strNUm: 0, delFlag: 0 }],
  status: "1"
});
const form3 = ref({
  level1: "",
  level2: "",
  level3: [{ name: "", sort: 1, strNUm: 0, delFlag: 0 }],
  status: "1"
});
const rules = ref({
  name: [{ required: true, message: "请输入", trigger: ["blur"] }],
  level1: [{ required: true, message: "请选择", trigger: ["blur", "change"] }],
  level2: [{ required: true, message: "请选择", trigger: ["blur", "change"] }],
  level3: [{ required: true, message: "请选择", trigger: ["blur", "change"] }]
});

const selectReview = (data, type) => {
  if (type === "add") {
    // 添加
    if (level.value === 2) {
      level1Class.value = [
        {
          categoryId: data.categoryId,
          name: data.name
        }
      ];
    } else if (level.value === 3) {
      level1Class.value = [
        {
          categoryId: data.parentId,
          name: data.parentName
        }
      ];
      level2Class.value = [
        {
          categoryId: data.categoryId,
          name: data.name
        }
      ];
    }
  } else {
    //编辑
    console.log("编辑");
    if (level.value === 2) {
      level1Class.value = [
        {
          categoryId: data.parentId,
          name: data.parentName
        }
      ];
    } else if (level.value === 3) {
      const parentObj = orgChildIdFindParent(data.categoryId, props.optionInfo.list, "categoryId");
      console.log("找到了父级===", parentObj);
      level1Class.value = [
        {
          categoryId: parentObj[0].categoryId,
          name: parentObj[0].name
        }
      ];
      level2Class.value = [
        {
          categoryId: data.parentId,
          name: data.parentName
        }
      ];
    }
  }
};

// // 根据子id找父id和name,返回值不包含查找的id和name
// const findParentsId = (treeData, id) => {
//   if (treeData.length == 0) return;
//   for (let i = 0; i < treeData.length; i++) {
//     if (treeData[i].categoryId == id) {
//       return [];
//     } else {
//       if (treeData[i].children) {
//         let res = findParentsId(treeData[i].children, id);
//         if (res !== undefined) {
//           return res.concat({ categoryId: treeData[i].categoryId, name: treeData[i].name }).reverse();
//         }
//       }
//     }
//   }
// };
// // 组织结构子id，找父id和name
// const orgChildIdFindParent = (childId, orgList = []) => {
//   const result = findParentsId(orgList, childId);
//   return result || [];
// };

const reviewForm = formData => {
  // 编辑的时候，数据回显操作
  console.log("编辑时，数据回显===", formData);
  const parentObj = orgChildIdFindParent(formData.categoryId, props.optionInfo.list, "categoryId");
  if (level.value === 2) {
    form2.value = {
      level1: formData.parentId,
      // level2: [{ name: formData.name, sort: formData.sortOrder, strNUm: formData.name.length }],
      level2: [
        {
          ...formData,
          sort: formData.sortOrder,
          strNUm: formData.name.length,
          image: formData.image ? [{ fileUrl: formData.image, fileId: formData.image.split("/").at(-1) }] : []
        }
      ],
      status: String(formData.status),
      tips: parentObj.length > 0 ? parentObj[0].remark : formData.remark
    };
  } else if (level.value === 3) {
    // const parentObj = orgChildIdFindParent(formData.categoryId, props.optionInfo.list);
    form3.value = {
      level1: parentObj[0].categoryId,
      level2: formData.parentId,
      // level3: [{ name: formData.name, sort: formData.sortOrder, strNUm: formData.name.length }],
      level3: [
        {
          ...formData,
          sort: formData.sortOrder,
          strNUm: formData.name.length,
          image: formData.image ? [{ fileUrl: formData.image, fileId: formData.image.split("/").at(-1) }] : []
        }
      ],
      status: String(formData.status),
      tips: parentObj.length > 0 ? parentObj[0].remark : formData.remark
    };
  } else if (level.value === 1) {
    if (props.optionInfo.type === "edit") {
      form1.value = {
        name: formData.name,
        sort: formData.sortOrder,
        status: String(formData.status),
        strNUm: formData.name.length,
        tips: formData.remark,
        image: formData.image ? [{ fileUrl: formData.image, fileId: formData.image.split("/").at(-1) }] : []
      };
    }
  }
};

const reviewLevel = formData => {
  const parentObj = orgChildIdFindParent(formData.categoryId, props.optionInfo.list, "categoryId");
  //添加的时候，回显父级分类
  console.log("添加的时候，回显父级分类");
  if (level.value === 2) {
    form2.value = {
      level1: formData.categoryId,
      level2: [{ name: "", sort: 1, strNUm: 0, delFlag: 0, image: [] }],
      tips: parentObj.length > 0 ? parentObj[0].remark : formData.remark,
      status: "1"
    };
  } else if (level.value === 3) {
    form3.value = {
      level1: formData.parentId,
      level2: formData.categoryId,
      level3: [{ name: "", sort: 1, strNUm: 0, delFlag: 0, image: [] }],
      tips: parentObj.length > 0 ? parentObj[0].remark : formData.remark,
      status: "1"
    };
  } else if (level.value === 1) {
    if (props.optionInfo.type === "add") {
      nextTick(() => {
        form1.value = {
          name: null,
          tips: "",
          sort: 1,
          status: "1",
          strNUm: 0
        };
        form1Ref.value.resetFields();
      });
    }
  }
};

const levelNameChange = item => {
  if (level.value !== 1) {
    item.strNUm = item.name.length;
  } else {
    form1.value.strNUm = form1.value.name.length;
  }
};
const addItem = () => {
  if (level.value === 2) {
    // 二级分类
    form2.value.level2.push({ name: "", sort: 1, strNUm: 0, delFlag: 0, image: [] });
  } else if (level.value === 3) {
    // 三级分类
    form3.value.level3.push({ name: "", sort: 1, strNUm: 0, delFlag: 0, image: [] });
  }
};
const delLevelItem = (item, index) => {
  if (level.value === 2) {
    //二级分类
    if (form2.value.level2.length <= 1) return ElMessage.error("至少保留一条数据");
    form2.value.level2.splice(index, 1);
    // if (props.optionInfo.type === "edit") {
    //   item.delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
    //   console.log("编辑的时候，删除操作特殊处理", form2.value);
    // } else {
    //   form2.value.level2.splice(index, 1);
    // }
  } else if (level.value === 3) {
    //三级分类
    if (form3.value.level3.length <= 1) return ElMessage.error("至少保留一条数据");
    form3.value.level3.splice(index, 1);
    // if (props.optionInfo.type === "edit") {
    //   item.delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
    //   console.log("编辑的时候，删除操作特殊处理", form3.value);
    // } else {
    //   form3.value.level3.splice(index, 1);
    // }
  }
};

const uploadSuccess = (file, fileList, form) => {
  form.image = fileList;
};

const closeDialog = () => {
  resetForm();
  emit("close");
};
const resetForm = () => {
  console.log("清空数据");
  if (level.value === 2) {
    //二级分类
    form2Ref.value.resetFields();
    form2.value.level2 = [{ name: "", sort: 1, strNUm: 0 }];
  } else if (level.value === 3) {
    // 三级分类
    form3Ref.value.resetFields();
    form3.value.level3 = [{ name: "", sort: 1, strNUm: 0 }];
  } else {
    form1Ref.value.resetFields();
    form1.value.strNUm = 0;
  }
};
const submit = async () => {
  let flag = true; //动态表单项是否全部填写完毕
  if (level.value === 2) {
    //二级分类
    for (let item of form2.value.level2) {
      if (item.name.trim().length <= 0) {
        flag = false;
      }
    }
    if (!flag) return ElMessage.error("请填写完表单必填项");
    await form2Ref.value.validate((valid, fields) => {
      if (valid) {
        console.log("submit!222===", form2.value);
        emit("submit", form2.value, props.optionInfo.type, level.value);
      } else {
        console.log("error submit!", fields);
      }
    });
  } else if (level.value === 3) {
    // 三级分类
    for (let item of form3.value.level3) {
      if (item.name.trim().length <= 0) {
        flag = false;
      }
    }
    if (!flag) return ElMessage.error("请填写完表单必填项");
    await form3Ref.value.validate((valid, fields) => {
      if (valid) {
        console.log("submit!");
        emit("submit", form3.value, props.optionInfo.type, level.value);
      } else {
        console.log("error submit!", fields);
      }
    });
  } else {
    await form1Ref.value.validate((valid, fields) => {
      if (valid) {
        console.log("submit!====", form1.value);
        emit("submit", form1.value, props.optionInfo.type, level.value);
      } else {
        console.log("error submit!", fields);
      }
    });
  }
};

defineExpose({
  resetForm
});
</script>

<style lang="scss" scoped>
.level2-list {
  display: flex;
  justify-content: space-between;
  width: 100%;
  &:not(:last-of-type) {
    margin-bottom: 10px;
  }
  .level2-sort-wrap {
    display: flex;
    // width: 400px;
    justify-content: flex-end;
    align-items: flex-start;
    span {
      display: inline-block;
      width: 64px;
      text-align: right;
      white-space: nowrap;
    }
    .image-box {
      margin: 0 10px;
      width: 90px;
    }
    .el-input {
      margin: 0 10px;
    }
    .del-icon {
      cursor: pointer;
      margin-left: 10px;
    }
  }
}
</style>
